package com.cskaoyan.market.service;

import com.cskaoyan.market.bo.WxCartSubmitBo;
import com.cskaoyan.market.bo.WxOrderBo;
import com.cskaoyan.market.bo.WxOrderGoodsBo;
import com.cskaoyan.market.bo.WxOrderInfoBo;
import com.cskaoyan.market.config.RelationMapping;
import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.util.ResponseUtil;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxOrderServiceImpl implements WxOrderService{

    @Autowired
    RelationMapping relationMapping;

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    SecurityManager securityManager;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Override
    public Object list(Integer showType, Integer page, Integer limit) {
        //直接从session域中获取数据
        SecurityUtils.setSecurityManager(securityManager);
        MarketUser user = (MarketUser) SecurityUtils.getSubject().getSession().getAttribute("user");

        Short low = 0;
        Short high = 0;
        switch (showType) {
            case 1:
                // 未付款
                low = 101;
                high = 103;
                break;
            case 2:
                // 已付款
                low = 201;
                high = 203;
                break;
            case 3:
                // 已发货
                low = 301;
                high = 303;
                break;
            case 4:
                // 已收货
                low = 401;
                high = 403;
                break;
            default:
                break;
        }
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.setOrderByClause("add_time desc");
        MarketOrderExample.Criteria orderExampleCriteria = marketOrderExample.createCriteria();
        if (showType != 0) {
            // 除了全部，其余都需要筛选
            orderExampleCriteria.andOrderStatusBetween(low, high);
        }
        orderExampleCriteria.andUserIdEqualTo(user.getId());
        orderExampleCriteria.andLogicalDeleted(true);
        PageHelper.startPage(page, limit);
        List<MarketOrder> marketOrderList = marketOrderMapper.selectByExample(marketOrderExample);

        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andLogicalDeleted(true);
        List<MarketOrderGoods> marketOrderGoodsList = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        // 封装数据
        List<WxOrderBo> wxOrderBoList = new ArrayList<>();
        for (MarketOrder marketOrder : marketOrderList) {
            WxOrderBo wxOrderBo = new WxOrderBo();
            wxOrderBo.setOrderStatusText(relationMapping.STATUS_MAP.get(marketOrder.getOrderStatus()));
            wxOrderBo.setAftersaleStatus(marketOrder.getAftersaleStatus());
            wxOrderBo.setIsGroupin(false);
            wxOrderBo.setOrderSn(marketOrder.getOrderSn());
            wxOrderBo.setActualPrice(marketOrder.getActualPrice());
            wxOrderBo.setId(marketOrder.getId());
            wxOrderBo.setHandleOption(relationMapping.OPTION_MAP.get(marketOrder.getOrderStatus()));

            // 封装订单商品
            List<WxOrderGoodsBo> wxOrderGoodsBoList = new ArrayList<>();
            for (MarketOrderGoods marketOrderGoods : marketOrderGoodsList) {
                if (marketOrder.getId() == marketOrderGoods.getOrderId()) {
                    wxOrderGoodsBoList.add(new WxOrderGoodsBo(marketOrderGoods.getNumber(), marketOrderGoods.getPicUrl(),
                            marketOrderGoods.getPrice(), marketOrderGoods.getId(), marketOrderGoods.getGoodsName(), marketOrderGoods.getSpecifications()));
                }
            }
            wxOrderBo.setGoodsList(wxOrderGoodsBoList);
            wxOrderBoList.add(wxOrderBo);
        }

        return ResponseUtil.okList(wxOrderBoList, marketOrderList);
    }

    @Override
    public Map<String, Object> detail(Integer orderId) {
        //直接从session域中获取数据
        SecurityUtils.setSecurityManager(securityManager);
        MarketUser user = (MarketUser) SecurityUtils.getSubject().getSession().getAttribute("user");

        // 订单信息
        MarketOrderExample orderExample = new MarketOrderExample();
        orderExample.createCriteria().andIdEqualTo(orderId).andUserIdEqualTo(user.getId());
        MarketOrder marketOrder = marketOrderMapper.selectOneByExample(orderExample);
        // 商品信息
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andLogicalDeleted(true);
        List<MarketOrderGoods> orderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        // 封装数据
        Map<String, Object> data = new HashMap<>();
        // 1
        String[] expressInfo = new String[0];
        data.put("expressInfo", expressInfo);
        // 2
        WxOrderInfoBo orderInfo = new WxOrderInfoBo();
        orderInfo.setExpName(relationMapping.SHIP_MAP.get(marketOrder.getShipChannel())); // 快递公司名称
        orderInfo.setConsignee(marketOrder.getConsignee());;
        orderInfo.setAddress(marketOrder.getAddress());
        orderInfo.setAddTime(marketOrder.getAddTime());
        orderInfo.setOrderSn(marketOrder.getOrderSn());
        orderInfo.setActualPrice(marketOrder.getActualPrice());
        orderInfo.setMobile(marketOrder.getMobile());
        orderInfo.setMessage(marketOrder.getMessage());
        orderInfo.setExpCode(marketOrder.getShipChannel()); // shipChannel
        orderInfo.setOrderStatusText(relationMapping.STATUS_MAP.get(marketOrder.getOrderStatus()));
        orderInfo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfo.setGoodsPrice(marketOrder.getGoodsPrice());
        orderInfo.setExpNo(marketOrder.getShipSn()); // 不知道，猜测(shipSn)
        orderInfo.setCouponPrice(marketOrder.getCouponPrice());
        orderInfo.setId(marketOrder.getId());
        orderInfo.setFreightPrice(marketOrder.getFreightPrice());
        orderInfo.setHandleOption(relationMapping.OPTION_MAP.get(marketOrder.getOrderStatus()));
        data.put("orderInfo", orderInfo);
        // 3
        data.put("orderGoods", orderGoods);

        return data;
    }

    // 取消订单-->用户取消，更改订单状态
    // 待付款-->取消订单
    @Override
    public void cancel(Integer orderId) {
        // 创建对象
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short)102);
        marketOrder.setId(orderId);
        // 更改订单信息
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    // 同cancel的处理方法，
    // 已发货-->申请退款中
    @Override
    public void refund(Integer orderId) {
        /**
         * 与cancel唯一的区别是需要退账户中的钱，
         * 可没有实现这块内容，所以此方法的操作与cancel方法一致
         */
        // 创建对象
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short)202);
        marketOrder.setId(orderId);
        // 订单信息
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    // 待评价-->删除订单
    @Override
    public void delete(Integer orderId) {
        // 订单信息
        marketOrderMapper.logicalDeleteByPrimaryKey(orderId);
        // 商品信息
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        marketOrderGoodsMapper.logicalDeleteByExample(marketOrderGoodsExample);
    }

    // 确认收货
    @Override
    public void confirm(Integer orderId) {
        // 更改订单状态
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short)401);
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public MarketOrderGoods getGoods(Integer orderId, Integer goodsId) {
        // 获取订单商品
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        marketOrderGoodsExample.createCriteria().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectOneByExample(marketOrderGoodsExample);
        return marketOrderGoods;
    }

    // 付款后，更改订单状态为已付款
    @Override
    public void prepay(Integer orderId) {
        // 更改订单状态
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short)201);
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Transactional
    @Override
    public Integer submit(WxCartSubmitBo wxCartSubmitBo) {
        //直接从session域中获取数据
        SecurityUtils.setSecurityManager(securityManager);
        MarketUser user = (MarketUser) SecurityUtils.getSubject().getSession().getAttribute("user");

        // addressId
        // message
        // 查询address表中得到地址信息加入到order表中
        MarketAddressExample addressExample = new MarketAddressExample();
        addressExample.createCriteria().andIdEqualTo(wxCartSubmitBo.getAddressId()).andUserIdEqualTo(user.getId());
        MarketAddress address = marketAddressMapper.selectOneByExample(addressExample);


        // cartId
        // 需要先从购物车中将需要的信息拿到
        List<MarketCart> marketCarts = new ArrayList<>();
        if (wxCartSubmitBo.getCartId() == 0) {
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andUserIdEqualTo(user.getId()).andCheckedEqualTo(true).andLogicalDeleted(true);
            marketCarts = marketCartMapper.selectByExample(marketCartExample);
            // 然后删除购物车中的记录（逻辑删除）
            marketCartMapper.logicalDeleteByExample(marketCartExample);
        } else {
            MarketCartExample marketCartExample = new MarketCartExample();
            marketCartExample.createCriteria().andIdEqualTo(wxCartSubmitBo.getCartId()).andUserIdEqualTo(user.getId()).andLogicalDeleted(true);
            MarketCart marketCart = marketCartMapper.selectOneByExample(marketCartExample);
            marketCartMapper.logicalDeleteByPrimaryKey(wxCartSubmitBo.getCartId());
            marketCarts.add(marketCart);
        }



//        // couponId 此处应该将优惠券的数量-1，获取优惠券详细信息
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxCartSubmitBo.getCouponId());
//        if (marketCoupon != null) {
//
//        }
//        // 查看优惠券库存，如果不为0则需要-1
//        if (marketCoupon.getTotal() > 0) {
//            // 说明优惠券不是无限量
//            MarketCoupon coupon = new MarketCoupon();
//            coupon.setId(marketCoupon.getId());
//            coupon.setTotal(coupon.getTotal() - 1);
//            marketCouponMapper.updateByPrimaryKeySelective(coupon);
//        }
        // userCouponId 设置优惠券状态为已使用
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setId(wxCartSubmitBo.getUserCouponId());
        marketCouponUser.setUserId(user.getId());
        marketCouponUser.setStatus((short)1);
        marketCouponUser.setCouponId(wxCartSubmitBo.getCouponId());
        marketCouponUserMapper.updateByPrimaryKey(marketCouponUser);


        // 创建order记录
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setUserId(user.getId());
        //
        String string = LocalDateTime.now().toString();
        char[] charArray = string.toCharArray();
        StringBuffer buffer = new StringBuffer();
        for (char c : charArray) {
            if (Character.isDigit(c)) {
                buffer.append(c);
            }
        }
        String baseOrderSn = buffer.toString();
        //
        marketOrder.setOrderSn(baseOrderSn); // 订单号怎么生成
        marketOrder.setOrderStatus((short)101);
        marketOrder.setAftersaleStatus((short)0);
        marketOrder.setConsignee(address.getName());
        marketOrder.setMobile(address.getTel());
        marketOrder.setAddress(address.getAddressDetail());
        marketOrder.setMessage(wxCartSubmitBo.getMessage());

        // 计算购物车中所有商品的总价格
        BigDecimal totalPrice = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            totalPrice = totalPrice.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
        }
        marketOrder.setGoodsPrice(totalPrice);
        marketOrder.setFreightPrice(new BigDecimal(8));
        if (marketCoupon == null) {
            marketOrder.setCouponPrice(BigDecimal.ZERO);
        } else {
            marketOrder.setCouponPrice(marketCoupon.getDiscount());
        }
        marketOrder.setIntegralPrice(new BigDecimal(0));
        marketOrder.setGrouponPrice(new BigDecimal(0));
        if (totalPrice.compareTo(new BigDecimal(88)) >= 0) {
            marketOrder.setOrderPrice(marketOrder.getGoodsPrice().subtract(marketOrder.getCouponPrice()));
        } else {
            marketOrder.setOrderPrice(marketOrder.getGoodsPrice().add(marketOrder.getFreightPrice()).subtract(marketOrder.getCouponPrice()));
        }
        marketOrder.setActualPrice(marketOrder.getOrderPrice().subtract(marketOrder.getIntegralPrice()));
        if (marketOrder.getActualPrice().compareTo(BigDecimal.ZERO) < 0) {
            marketOrder.setActualPrice(BigDecimal.ZERO);
        }
        marketOrder.setPayId("123413");
        marketOrder.setPayTime(LocalDateTime.now());

        // 快递
        marketOrder.setShipSn("2345252456345624");
        marketOrder.setShipChannel("YD");
        marketOrder.setShipTime(LocalDateTime.now());

//        // 退款
//        marketOrder.setRefundAmount();
//        marketOrder.setRefundType();
//        marketOrder.setRefundContent();
//        marketOrder.setRefundTime();

//        marketOrder.setConfirmTime(); // 收货时间
//        marketOrder.setComments(); // 评论

//        marketOrder.setEndTime();
        marketOrder.setAddTime(LocalDateTime.now());
//        marketOrder.setUpdateTime();
        marketOrder.setDeleted(false);
        marketOrderMapper.insertSelective(marketOrder);
        MarketOrderExample orderExample = new MarketOrderExample();
        orderExample.createCriteria().andOrderSnEqualTo(baseOrderSn.toString());
        MarketOrder order = marketOrderMapper.selectOneByExample(orderExample);


        // 创建orderGoods记录
        for (MarketCart marketCart : marketCarts) {
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            marketOrderGoods.setOrderId(order.getId());
            marketOrderGoods.setGoodsId(marketCart.getGoodsId());
            marketOrderGoods.setGoodsName(marketCart.getGoodsName());
            marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
            marketOrderGoods.setProductId(marketCart.getProductId());
            marketOrderGoods.setNumber(marketCart.getNumber());
            marketOrderGoods.setPrice(marketCart.getPrice());
            marketOrderGoods.setSpecifications(marketCart.getSpecifications());
            marketOrderGoods.setPicUrl(marketCart.getPicUrl());
            marketOrderGoods.setComment(0);
            marketOrderGoods.setAddTime(LocalDateTime.now());
            marketOrderGoods.setDeleted(false);
            marketOrderGoodsMapper.insert(marketOrderGoods);
        }
        return order.getId();
    }

}
